package com.example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {

    ProductDAO productDAO = new ProductDAO();


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("getAll".equals(action)){
            //为查看所有商品页面准备数据

            List<Product> products = productDAO.findAll();

            // 将查询结果存储到request对象中
            request.setAttribute("products", products);

            // 转发请求到JSP页面
            request.getRequestDispatcher("/product.jsp").forward(request, response);
        } else if ("edit".equals(action)) {
            System.out.println("实现编辑操作的逻辑");
        }else {
            // 实现删除逻辑
            String idFromFront = request.getParameter("id");
            boolean flag = productDAO.deleteProductByID(Integer.valueOf(idFromFront));
            if (flag){
                // 删除成功
                response.sendRedirect(request.getContextPath()+"/products?action=getAll");
            }else {
                // 删除失败
                request.setAttribute("msg","删除失败");
                request.getRequestDispatcher("/products?action=getAll").forward(request,response);
            }

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name  = req.getParameter("name");
        String description  = req.getParameter("description");
        String price  = req.getParameter("price");
        Product product = new Product();
        product.setName(name);
        product.setDescription(description);
        product.setPrice(Double.parseDouble(price));
        boolean flag = productDAO.addProduct(product);

        if (flag){
            // 添加成功
            resp.sendRedirect(req.getContextPath()+"/products?action=getAll");
        }else {
            // 添加失败
            req.setAttribute("msg","添加失败");
            req.getRequestDispatcher("/products?action=getAll").forward(req,resp);
        }

    }
}